/**
 * 收藏页面逻辑
 */
document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    const elements = {
        favoritesGrid: document.getElementById('favorites-grid'),
        emptyFavorites: document.getElementById('empty-favorites')
    };
    
    // 状态
    const state = {
        currentPage: 1,
        hasMorePages: true,
        isLoading: false
    };
    
    /**
     * 初始化页面
     */
    async function init() {
        // 加载收藏列表
        await loadFavorites();
        
        // 绑定滚动事件
        window.addEventListener('scroll', debounce(() => {
            if (state.isLoading || !state.hasMorePages) return;
            
            const scrollPosition = window.scrollY + window.innerHeight;
            const pageHeight = document.body.scrollHeight - 200; // 提前200px触发
            
            if (scrollPosition > pageHeight) {
                loadMoreFavorites();
            }
        }, 200));
    }
    
    /**
     * 加载收藏列表
     */
    async function loadFavorites() {
        if (state.isLoading) return;
        
        try {
            state.isLoading = true;
            
            // 第一次加载时显示加载中
            if (state.currentPage === 1) {
                elements.favoritesGrid.innerHTML = `
                    <div class="loading-spinner">
                        <div class="spinner"></div>
                        <p>加载中...</p>
                    </div>
                `;
            }
            
            // 请求收藏数据
            const response = await API.getFavorites(state.currentPage, 10);
            
            // 更新分页状态
            state.hasMorePages = response.pagination.current_page < response.pagination.total_pages;
            
            // 渲染收藏列表
            if (state.currentPage === 1) {
                elements.favoritesGrid.innerHTML = '';
            }
            renderFavorites(response.data);

        } catch (error) {
            console.error('加载收藏失败:', error);
            showError('加载收藏失败，请刷新重试');
        } finally {
            state.isLoading = false;
        }
    }
    
    /**
     * 加载更多收藏
     */
    function loadMoreFavorites() {
        if (state.hasMorePages && !state.isLoading) {
            state.currentPage++;
            loadFavorites();
        }
    }
    
    /**
     * 渲染收藏列表
     */
    function renderFavorites(favorites) {
        // 检查是否有收藏
        if (!favorites || favorites.length === 0) {
            if (state.currentPage === 1) {
                // 移除空状态的hidden类，使其显示
                elements.emptyFavorites.classList.remove('hidden');
                elements.favoritesGrid.innerHTML = '';
            }
            return;
        } else {
            // 确保空状态隐藏
            elements.emptyFavorites.classList.add('hidden');
        }
        
        // 创建壁纸卡片
        favorites.forEach(wallpaper => {
            const wallpaperCard = createWallpaperCard(wallpaper);
            elements.favoritesGrid.appendChild(wallpaperCard);
        });
        
        // 初始化懒加载
        initLazyLoading();
    }
    
    /**
     * 创建壁纸卡片
     */
    function createWallpaperCard(wallpaper) {
        const card = document.createElement('div');
        card.className = 'wallpaper-card';
        card.dataset.id = wallpaper.id;
        
        card.innerHTML = `
            <div class="wallpaper-actions">
                <div class="action-icon favorite active" data-id="${wallpaper.id}">
                    <img src="icon/favorite-s-fill.svg" alt="图标" width="24" height="24">
                </div>
            </div>
            <img class="wallpaper-img lazy-image" data-src="${API.getWallpaperThumbnailUrl(wallpaper.id)}" alt="${wallpaper.category}壁纸">
            <div class="wallpaper-info">
                <div class="wallpaper-category">${getCategoryName(wallpaper.category)}</div>
            </div>
        `;
        
        // 点击壁纸跳转到详情页
        card.addEventListener('click', (e) => {
            // 避免点击收藏按钮时跳转
            if (!e.target.closest('.action-icon')) {
                Storage.addRecentlyViewed(wallpaper.id);
                window.location.href = `detail.html?id=${wallpaper.id}`;
            }
        });
        
        // 收藏按钮点击
        const favoriteBtn = card.querySelector('.action-icon.favorite');
        favoriteBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止冒泡，避免触发卡片点击
            removeFromFavorites(favoriteBtn, card);
        });
        
        return card;
    }
    
    /**
     * 从收藏中移除
     */
    async function removeFromFavorites(buttonElement, cardElement) {
        const wallpaperId = buttonElement.dataset.id;
        
        try {
            // 移除收藏
            await API.removeFromFavorites(wallpaperId);
            
            // 添加过渡效果
            cardElement.classList.add('removing');
            
            // 等待过渡完成后从DOM中移除
            setTimeout(() => {
                cardElement.remove();
                
                // 检查是否还有收藏
                if (elements.favoritesGrid.children.length === 0) {
                    elements.emptyFavorites.classList.remove('hidden');
                }
            }, 300);
            
        } catch (error) {
            console.error('移除收藏失败:', error);
            showToast('移除失败，请重试');
        }
    }
    
    /**
     * 根据分类ID获取分类名称
     */
    function getCategoryName(categoryId) {
        const categoryMap = {
            'nature': '自然风光',
            'city': '城市建筑',
            'abstract': '抽象艺术',
            'minimal': '简约风格',
            'dark': '暗色系',
            'bright': '亮色系'
        };
        
        return categoryMap[categoryId] || categoryId;
    }
    
    /**
     * 显示错误提示
     */
    function showError(message) {
        elements.favoritesGrid.innerHTML = `
            <div class="error-message">
                <i class="ri-error-warning-line"></i>
                <p>${message}</p>
                <button onclick="window.location.reload()">重试</button>
            </div>
        `;
    }
    
    /**
     * 显示反馈提示
     */
    function showToast(message) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = message;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 触发动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // 自动移除
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 2000);
    }
    
    /**
     * 初始化图片懒加载
     */
    function initLazyLoading() {
        const lazyImages = document.querySelectorAll('.lazy-image');
        
        // 使用Intersection Observer实现懒加载
        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        const src = img.dataset.src;
                        
                        // 创建图片对象
                        const tempImg = new Image();
                        tempImg.onload = () => {
                            img.src = src;
                            img.classList.remove('lazy-image');
                        };
                        tempImg.src = src;
                        
                        // 停止观察
                        imageObserver.unobserve(img);
                    }
                });
            }, {
                rootMargin: '50px 0px'
            });
            
            lazyImages.forEach(img => {
                imageObserver.observe(img);
            });
        } else {
            // 回退: 简单地加载所有图片
            lazyImages.forEach(img => {
                img.src = img.dataset.src;
                img.classList.remove('lazy-image');
            });
        }
    }
    
    /**
     * 防抖函数
     */
    function debounce(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args);
            }, wait);
        };
    }
    
    // 初始化
    init();
}); 